package ncu.me.musicplayer;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;

import ncu.me.musicplayer.entity.MusicInfo;
import ncu.me.musicplayer.player.MusicManager;

/**
 * @Author ye
 * @Date 2020/6/4 16:23
 * @Version 1.0
 */
public class MyService extends Service {

    int notificationId = 2;
    String channelId = "1234";
    String channelName = "音乐";
    MyBroadcastReceiver myBroadcastReceiver;
    public static final String RECEIVER_ACTION = "ncu.me.receiver";
    public static final int ACTION_PREVIOUS=1;
    public static final int ACTION_NEXT=2;
    public static final int ACTION_PAUSE=3;
    public static final int ACTION_RESUME=4;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * Called by the system when the service is first created.  Do not call this method directly.
     */
    @Override
    public void onCreate() {
        super.onCreate();
        //注册监听
        MusicManager.getInstance().addIndexChangedListener(this, index -> {
            NotificationManager systemService = getSystemService(NotificationManager.class);
            systemService.notify(notificationId,getNotification());
        });
        MusicManager.getInstance().addStateChangedListener(this, new MusicManager.PlayStateChangedListener() {
            @Override
            public void onChange(boolean isPlaying) {
                update();
            }
        });

        //注册广播
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RECEIVER_ACTION);
        registerReceiver(myBroadcastReceiver,intentFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(notificationId,getNotification());
        return super.onStartCommand(intent, flags, startId);
    }
    public void update(){
        NotificationManager systemService = getSystemService(NotificationManager.class);
        systemService.notify(notificationId,getNotification());
    }
    Notification getNotification(){
        NotificationChannel channel = new NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_LOW);
        NotificationManager systemService = getSystemService(NotificationManager.class);
        systemService.createNotificationChannel(channel);

        RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.notification_view);
        remoteViews.setImageViewResource(R.id.music_thumb,R.drawable.music);
        remoteViews.setImageViewResource(R.id.btn_previous,R.drawable.previous);
        remoteViews.setImageViewResource(R.id.btn_next,R.drawable.next);
        if (MusicManager.getInstance().isPlaying()){
            remoteViews.setImageViewResource(R.id.btn_play,R.drawable.pause);
        }else {
            remoteViews.setImageViewResource(R.id.btn_play,R.drawable.play);
        }

        Intent previousIntent = new Intent(RECEIVER_ACTION);
        previousIntent.putExtra("data",ACTION_PREVIOUS);
        Intent nextIntent = new Intent(RECEIVER_ACTION);
        nextIntent.putExtra("data",ACTION_NEXT);
        Intent playIntent = new Intent(RECEIVER_ACTION);
        if (MusicManager.getInstance().isPlaying()){
            playIntent.putExtra("data",ACTION_PAUSE);
        }else {
            playIntent.putExtra("data",ACTION_RESUME);
        }
        PendingIntent pendingIntentPrevious = PendingIntent.getBroadcast(this,11,previousIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pendingIntentNext = PendingIntent.getBroadcast(this,12,nextIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pendingIntentPlay = PendingIntent.getBroadcast(this,13,playIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btn_previous,pendingIntentPrevious);
        remoteViews.setOnClickPendingIntent(R.id.btn_next,pendingIntentNext);
        remoteViews.setOnClickPendingIntent(R.id.btn_play,pendingIntentPlay);

        MusicInfo info = MusicManager.getInstance().get();
        if (info != null){
            remoteViews.setTextViewText(R.id.music_name, info.getSongName());
        }
        Intent intent = new Intent();
        intent.setClass(this,MusicActivity.class);
        Notification notification = new Notification.Builder(this, channelId)
                .setCustomContentView(remoteViews)
                .setSmallIcon(R.drawable.music)
                .build();

        return notification;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消注册
        MusicManager.getInstance().removeIndexChangedListener(this);
        MusicManager.getInstance().removeStateChangedListener(this);

        //取消注册广播
        unregisterReceiver(myBroadcastReceiver);
    }

    /**
     * 处理来自通知的广播
     */
    static class MyBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            int data = intent.getIntExtra("data", 0);

            switch (data){
                case ACTION_PREVIOUS:{
                    MusicManager.getInstance().previous();
                    break;
                }
                case ACTION_NEXT:{
                    MusicManager.getInstance().next();
                    break;
                }
                case ACTION_PAUSE:{
                    MusicManager.getInstance().pause();
                    break;
                }
                case ACTION_RESUME:{
                    MusicManager.getInstance().resume();
                    break;
                }
                default:
            }
        }
    }
}
